import pymysql
from util.comm.msg_util import msg

class MyMysql():
    def __init__(self):
        super().__init__()

    def search(self, config, sql):
        # 创建数据库连接
        # path = getPath()
        try:
            # cx_Oracle.init_oracle_client(lib_dir=r"%s\%s" % (path, 'instantclient_21_3'))
            pymysql.install_as_MySQLdb()
        except:
            pass

        try:
            conn = pymysql.connect(user=config['user'], password=config['password'],
                                          host=config['host'], port=config['port'],
                                          database=config['service_name'])
        except pymysql.err.OperationalError as e:
            msg("mysql连接失败，请检查连接配置; %s" % e)
            return "0"
        # 创建游标
        cursor = conn.cursor()

        # 执行查询语句
        cursor.execute(sql)

        # 获取查询结果
        result = cursor.fetchall()

        field_list = []
        # 获取查询结果
        for row in result:
            field_list.append(row)

        # 关闭游标和连接
        cursor.close()
        conn.close()

        return field_list

    def searchObj(self, config, sql):
        # 创建数据库连接
        # path = getPath()
        try:
            # cx_Oracle.init_oracle_client(lib_dir=r"%s\%s" % (path, 'instantclient_21_3'))
            pymysql.install_as_MySQLdb()
        except:
            pass

        try:
            conn = pymysql.connect(user=config['user'], password=config['password'],
                                          host=config['host'], port=config['port'],
                                          database=config['service_name'])
        except pymysql.err.OperationalError as e:
            msg("mysql连接失败，请检查连接配置; %s" % e)
            return "0"
        # 创建游标
        cursor = conn.cursor()

        # 执行查询语句
        cursor.execute(sql)

        # 获取查询结果
        result = cursor.fetchall()

        # 获取列的名称
        column_names = [desc[0].lower() for desc in cursor.description]

        field_list = []
        # 获取查询结果
        for row in cursor:
            field_list.append({col: value for col, value in zip(column_names, row)})

        # 关闭游标和连接
        cursor.close()
        conn.close()

        return field_list